package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.school.domain.dto.ImportDanWeiInfo;
import com.ruoyi.school.domain.dto.ImportStudentInfo;
import com.ruoyi.school.domain.dto.ImportTeacherInfo;
import com.ruoyi.school.service.PacDanweiService;
import com.ruoyi.school.service.PacTeacherService;
import com.ruoyi.school.service.StudentService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Resource
    private StudentService studentService;

    @Resource
    private PacTeacherService teacherService;

    @Resource
    private PacDanweiService danweiService;

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Integer type) throws Exception
    {
        String message;

        // 1 学生 2老师 3用人单位
        if(type == 1){
            ExcelUtil<ImportStudentInfo> util = new ExcelUtil<>(ImportStudentInfo.class);
            String operName = getUsername();
            List<ImportStudentInfo> studentList = util.importExcel(file.getInputStream());
            message = userService.importStudent(studentList, operName);
        }else if(type == 2){
            ExcelUtil<ImportTeacherInfo> util = new ExcelUtil<>(ImportTeacherInfo.class);
            String operName = getUsername();
            List<ImportTeacherInfo> teacherInfoList = util.importExcel(file.getInputStream());
            message = userService.importTeacher(teacherInfoList, operName);
        }else {
            ExcelUtil<ImportDanWeiInfo> util = new ExcelUtil<>(ImportDanWeiInfo.class);
            String operName = getUsername();
            List<ImportDanWeiInfo> danWeiInfoList = util.importExcel(file.getInputStream());
            message = userService.importDanWei(danWeiInfoList, operName);
        }

        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response,"用户数据");
    }

    @PostMapping("/importTemplate1")
    public void importTemplate1(HttpServletResponse response)
    {
        ExcelUtil<ImportStudentInfo> util = new ExcelUtil<>(ImportStudentInfo.class);
        List<ImportStudentInfo> templateList = new ArrayList<>();
        ImportStudentInfo studentInfo = new ImportStudentInfo();
        studentInfo.setStuNum("0000001");
        studentInfo.setStuName("张三");
        studentInfo.setBirth("2005-01-01");
        studentInfo.setSex("男");
        studentInfo.setNation("汉");
        studentInfo.setYearEnrollment("2020");
        studentInfo.setDomicile("上海");
        studentInfo.setPoliticalOutlook("群众");
        studentInfo.setFaculties("计算机科学与技术");
        studentInfo.setMajor("软件工程");
        studentInfo.setBigTeam("大队");
        studentInfo.setStuClass("软件工程205");
        studentInfo.setSmallTeam("区队");
        studentInfo.setPhone("12345678901");
        templateList.add(studentInfo);
        util.exportExcel(response, templateList,"学生数据");
    }

    @PostMapping("/importTemplate2")
    public void importTemplate2(HttpServletResponse response)
    {
        ExcelUtil<ImportTeacherInfo> util = new ExcelUtil<>(ImportTeacherInfo.class);
        List<ImportTeacherInfo> templateList = new ArrayList<>();
        ImportTeacherInfo teacherInfo = new ImportTeacherInfo();
        teacherInfo.setTeacherNum("000002");
        teacherInfo.setTeacherName("张老师");
        teacherInfo.setBirth("1990-01-01");
        teacherInfo.setSex("男");
        teacherInfo.setTitle("助教");
        teacherInfo.setEducation("本科");
        teacherInfo.setDegree("本科");
        teacherInfo.setFaculties("计算机科学与技术");
        teacherInfo.setPhone("12345678901");
        teacherInfo.setTeacherType("专业教师、中队长");
        templateList.add(teacherInfo);
        util.exportExcel(response, templateList,"老师数据");
    }

    @PostMapping("/importTemplate3")
    public void importTemplate3(HttpServletResponse response)
    {
        ExcelUtil<ImportDanWeiInfo> util = new ExcelUtil<>(ImportDanWeiInfo.class);
        List<ImportDanWeiInfo> templateList = new ArrayList<>();
        ImportDanWeiInfo danWeiInfo = new ImportDanWeiInfo();
        danWeiInfo.setName("张三");
        danWeiInfo.setBirth("1990-01-01");
        danWeiInfo.setSex("男");
        danWeiInfo.setDuty("职级名称");
        danWeiInfo.setUnit("单位名称");
        danWeiInfo.setPhone("13888888888");
        danWeiInfo.setCity("南京市");
        templateList.add(danWeiInfo);
        util.exportExcel(response, templateList,"单位数据");
    }


    /**
     * 根据用户编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        return ajax;
    }

    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 导出学生数据
     */
    @PostMapping("/exportStudent")
    public void exportStudent(HttpServletResponse response){
        List<ImportStudentInfo> list = studentService.selectList();
        ExcelUtil<ImportStudentInfo> util = new ExcelUtil<>(ImportStudentInfo.class);
        util.exportExcel(response, list, "学生数据");
    }

    /**
     * 导出老师数据
     */
    @PostMapping("/exportTeacher")
    public void exportTeacher(HttpServletResponse response){
        List<ImportTeacherInfo> list = teacherService.selectList();
        ExcelUtil<ImportTeacherInfo> util = new ExcelUtil<>(ImportTeacherInfo.class);
        util.exportExcel(response, list, "老师数据");
    }

    /**
     * 导出单位数据
     */
    @PostMapping("/exportDanwei")
    public void exportDamweo(HttpServletResponse response){
        List<ImportDanWeiInfo> list = danweiService.selectList();
        ExcelUtil<ImportDanWeiInfo> util = new ExcelUtil<>(ImportDanWeiInfo.class);
        util.exportExcel(response, list, "单位数据");
    }
}
